﻿Public Class PatternDialogV2

    Public Period_ID As Integer
    Public Allocation_ID As String
    Public Payment_ID As String
    Public RID As String
    Public IsCustom As Boolean

   

    Dim TheDataView As DataView

    Private Sub LoadPaymentTypeBox()


        Dim sql = "select * from Payment_Types where Period_ID = " & Period_ID

        If Payment_ID <> "" Then
            sql = sql & " and Payment_ID = '" & Payment_ID & "'"
        Else
            sql = sql & " order by Payment_Description"
        End If

        LoadComboBox(PaymentTypeBox, sql, "Payment_ID", "Payment_Description")

        If Payment_ID <> "" Then

            PaymentTypeBox.Enabled = False

        Else

            PaymentTypeBox.Enabled = True

        End If

    End Sub

    Private Sub PatternDialogV2_Shown(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Shown
        If RID = "" Then

            'national or custom pattern
            If IsCustom = False Then
                'national pattern
                PaymentTypeBox.Visible = True
                LoadPaymentTypeBox()
                RecalcButton.Visible = False
                FundingLabel.Visible = False
                TotalFundingBox.Visible = False

            Else
                'custom pattern
                RecalcButton.Visible = False
                PaymentTypeBox.Visible = False
                FundingLabel.Visible = False
                TotalFundingBox.Visible = False
                LoadCustomPattern()
                CalculatePercentTotal()

            End If
            

        Else
            'provider pattern
            PaymentTypeBox.Visible = False
            LoadProviderPattern()
            RecalcButton.Visible = True
            FundingLabel.Visible = True
            TotalFundingBox.Visible = True


        End If



    End Sub

    Private Sub PaymentTypeBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PaymentTypeBox.SelectedIndexChanged

        If PaymentTypeBox.Items.Count = 0 Then Exit Sub

        LoadNationalPattern()
        CalculatePercentTotal()


    End Sub

    Private Sub LoadCustomPattern()


        Try
            TheDataView = LoadDataView("exec dbo.spBudget_Custom_Pattern '" & BudgetsFormV2.CustomPatternBox.SelectedValue & "'")

        Catch ex As Exception
            Exit Sub
        End Try
        HeaderLabel.Text = DirectCast(BudgetsFormV2.CustomPatternBox.DataSource, DataView)(BudgetsFormV2.CustomPatternBox.SelectedIndex)("Pattern_Description").ToString


        FundingBox.Visible = False
        FundingLabel.Visible = False
        TotalFundingBox.Visible = False

        DateLabel.DataBindings.Clear()
        DateLabel.DataBindings.Add(New System.Windows.Forms.Binding("Text", TheDataView, "Friendly_Date"))

        PercentBox.DataBindings.Clear()
        PercentBox.DataBindings.Add(New System.Windows.Forms.Binding("Text", TheDataView, "Percentage_String"))

        TheRepeater.DataSource = TheDataView

        RemoveHandler TheDataView.ListChanged, New System.ComponentModel.ListChangedEventHandler(AddressOf OnNationalDVChanged)
        AddHandler TheDataView.ListChanged, New System.ComponentModel.ListChangedEventHandler(AddressOf OnNationalDVChanged)

    End Sub

    Private Sub LoadNationalPattern()


        Try
            If Payment_ID = "" Then
                TheDataView = LoadDataView("select Payment_Date as Month, '0%' as Percentage_String, DATENAME(MM, Payment_Date ) + ' ' + CAST(YEAR(Payment_Date ) AS VARCHAR(4)) as Friendly_Date, 0 as Frozen from Payment_Dates where Payment_ID = " & PaymentTypeBox.SelectedValue & " order by Payment_Date ")
            Else
                TheDataView = LoadDataView("exec spBudget_national_Pattern @Period_ID = " & Period_ID & ", @Allocation_ID = '" & Allocation_ID & "'")
            End If

        Catch ex As Exception
            Exit Sub
        End Try
        HeaderLabel.Text = "Payment Type"

        FundingBox.Visible = False
        FundingLabel.Visible = False
        TotalFundingBox.Visible = False

        DateLabel.DataBindings.Clear()
        DateLabel.DataBindings.Add(New System.Windows.Forms.Binding("Text", TheDataView, "Friendly_Date"))

        PercentBox.DataBindings.Clear()
        PercentBox.DataBindings.Add(New System.Windows.Forms.Binding("Text", TheDataView, "Percentage_String"))

        TheRepeater.DataSource = TheDataView

        RemoveHandler TheDataView.ListChanged, New System.ComponentModel.ListChangedEventHandler(AddressOf OnNationalDVChanged)
        AddHandler TheDataView.ListChanged, New System.ComponentModel.ListChangedEventHandler(AddressOf OnNationalDVChanged)

    End Sub

    Private Sub LoadProviderPattern()


        Try
     
            TheDataView = LoadDataView("exec spBudget_Provider_Pattern @Period_ID = " & Period_ID & ", @Allocation_ID = '" & Allocation_ID & "', @RID = '" & RID & "'")

        Catch ex As Exception
            Exit Sub
        End Try
        HeaderLabel.Text = BudgetsFormV2.ProviderBox.zSelectedProvider.ProviderName

        FundingBox.Visible = True
        FundingLabel.Visible = True
        TotalFundingBox.Visible = True

        DateLabel.DataBindings.Clear()
        DateLabel.DataBindings.Add(New System.Windows.Forms.Binding("Text", TheDataView, "Friendly_Date"))

        PercentBox.DataBindings.Clear()
        PercentBox.DataBindings.Add(New System.Windows.Forms.Binding("Text", TheDataView, "Percentage_String"))

        FundingBox.DataBindings.Clear()
        FundingBox.DataBindings.Add(New System.Windows.Forms.Binding("Text", TheDataView, "Month_Total_String"))

        TheRepeater.DataSource = TheDataView

        RemoveHandler TheDataView.ListChanged, AddressOf OnNationalDVChanged
        AddHandler TheDataView.ListChanged, AddressOf OnNationalDVChanged

        CalculateFundingTotal()
        CalculatePercentTotal()



    End Sub

    Private Sub OnNationalDVChanged(ByVal sender As Object, ByVal args As System.ComponentModel.ListChangedEventArgs)
        'Console.WriteLine("ListChanged:")
        'Console.WriteLine(vbTab & "    Type = " & System.Enum.GetName(args.ListChangedType.GetType(), args.ListChangedType))
        'Console.WriteLine(vbTab & "OldIndex = " & args.OldIndex)
        'Console.WriteLine(vbTab & "NewIndex = " & args.NewIndex)

        'MessageBox.Show("    Type = " & System.Enum.GetName(args.ListChangedType.GetType(), args.ListChangedType))
        CalculatePercentTotal()
        CalculateFundingTotal()

    End Sub

    Private Function CalculatePercentTotal() As Decimal

        Dim r As DataRowView
        Dim p As Decimal = 0

        If TheRepeater.DataSource Is Nothing Then
            Return 0
        End If

        For Each r In TheRepeater.DataSource

            Try
                p = p + r("Percentage_String").ToString.Replace("%", "")
            Catch ex As Exception

            End Try



        Next

        TotalPercentBox.Text = Math.Round(p, 2).ToString & "%"


        If Math.Round(p) <> 100 Then
            TotalPercentBox.BackColor = Color.Red

        Else
            TotalPercentBox.Text = "100%"
            TotalPercentBox.BackColor = Color.Transparent

        End If

        Return Math.Round(p, 2)
        

    End Function

    Private Function PercentageLeft() As Decimal

        Dim r As DataRowView
        Dim p As Decimal = 0

        If TheRepeater.DataSource Is Nothing Then
            Return 0
        End If

        For Each r In TheRepeater.DataSource

            If r("Frozen") = 0 Then
                Try
                    p = p + r("Percentage_String").ToString.Replace("%", "")
                Catch ex As Exception

                End Try

            End If

        Next

        Return p

    End Function

    Private Function FundingLeft() As Decimal

        Dim r As DataRowView
        Dim f As Decimal = 0

        If TheRepeater.DataSource Is Nothing Then
            Return 0
        End If

        For Each r In TheRepeater.DataSource

            If r("Frozen") = 0 Then
                Try
                    f = f + r("Month_Total_String").ToString.Replace("£", "").Replace(",", "")
                Catch ex As Exception

                End Try

            End If

        Next

        Return f

    End Function

    Private Sub RecalcPercentage()

        Dim r As DataRowView

        Dim f As Decimal

        Dim fc As Decimal
        Dim a As Decimal


        f = CalculateFundingTotal()

        If TotalFundingBox.BackColor = Color.Red Then
            MessageBox.Show("Can't recalculate percentage, because the funding total does not match the allocation", "Percentage cannot be calculated", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If


        If f = 0 Then Exit Sub

        For Each r In TheRepeater.DataSource

            Try

                fc = r("Month_Total_String").ToString.Replace("£", "").Replace(",", "")
            Catch ex As Exception

                fc = 0
            End Try



            a = (fc / f) * 100

            a = Math.Round(a, 3)

            r("Percentage_String") = a.ToString & "%"



        Next


        TheRepeater.DataSource = TheDataView

        CalculatePercentTotal()

    End Sub

    Private Sub RecalcFunding()

        If CalculatePercentTotal() <> 100 Then Exit Sub

        Dim r As DataRowView

        Dim f As Decimal
        Dim p As Decimal

        Dim a As Decimal


        f = CalculateFundingTotal()



        For Each r In TheRepeater.DataSource

            If r("Frozen") = 0 Then
                Try
                    p = r("Percentage_String").ToString.Replace("%", "")

                Catch ex As Exception
                    p = 0

                End Try

                a = (p / 100) * f

                r("Month_Total_String") = a.ToString("c")
            
            End If

        Next

        TheRepeater.DataSource = TheDataView
        CalculateFundingTotal()


    End Sub

    Private Function CalculateFundingTotal() As Decimal

        If TotalFundingBox.Visible = False Then
            Return 0
        End If

        Dim r As DataRowView
        Dim f As Decimal = 0
        Dim fo As Decimal = 0


        If TheRepeater.DataSource Is Nothing Then
            Return 0
        End If

        For Each r In TheRepeater.DataSource

            Try
                f = f + r("Month_Total_String").ToString.Replace("£", "").Replace(",", "")
                fo = fo + r("Month_Total")
            Catch ex As Exception

            End Try



        Next

        TotalFundingBox.Text = f.ToString("c")

        If f <> fo Then
            TotalFundingBox.BackColor = Color.Red
        Else
            TotalFundingBox.BackColor = Color.Transparent

        End If

        Return Math.Round(fo, 2)

    End Function


    Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click

        'If RID <> "" Then
        '    RecalcPercentage()
        'End If

        'validate

        'no month should be more than 100%

        If TheRepeater.DataSource Is Nothing Then Exit Sub

        Dim r As DataRowView

        For Each r In TheRepeater.DataSource
            Dim p As Decimal

            Try
                p = r("Percentage_String").ToString.Replace("%", "")
            Catch ex As Exception
                p = 0
            End Try

            If p > 100 Then
                MessageBox.Show("No month can be more than 100%", "Percentage values are not valid", MessageBoxButtons.OK, MessageBoxIcon.Error)
                Exit Sub
            End If

        Next


        If Math.Round(CalculatePercentTotal()) <> 100 Then
            MessageBox.Show("The total percentage does not equal 100%.  Please make sure it equals 100% before continuing.", "Percentage is not 100%", MessageBoxButtons.OK, MessageBoxIcon.Error)
            Exit Sub
        End If

        If RID = "" And IsCustom = False Then
            If MessageBox.Show("The payments will now be calculated.  Depending on the amount of providers to be updated, this could take some time.  Are you sure you want to continue?", "Do you want to continue?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                Exit Sub
            End If
        End If

        DialogResult = Windows.Forms.DialogResult.OK


    End Sub

    Private Sub TheRepeater_DrawItem(ByVal sender As System.Object, ByVal e As Microsoft.VisualBasic.PowerPacks.DataRepeaterItemEventArgs) Handles TheRepeater.DrawItem
        Dim ThePanel As FlowLayoutPanel = TryCast(e.DataRepeaterItem.Controls("FlowPanel"), FlowLayoutPanel)

        If Not ThePanel Is Nothing Then
            Dim ThePercentBox As TextBox = TryCast(ThePanel.Controls("PercentBox"), TextBox)
            Dim TheFundingBox As TextBox = TryCast(ThePanel.Controls("FundingBox"), TextBox)

            If TheRepeater.DataSource(e.DataRepeaterItem.ItemIndex)("Frozen") = 1 Then
                ThePanel.BackColor = Color.LightBlue
                ThePercentBox.Enabled = False
                TheFundingBox.Enabled = False


            Else
                ThePanel.BackColor = Color.Transparent
                ThePercentBox.Enabled = True
                TheFundingBox.Enabled = True

            End If

            'add handler for the input box
            RemoveHandler ThePercentBox.Leave, AddressOf MakePercent
            RemoveHandler ThePercentBox.Enter, AddressOf MakeNumber

            AddHandler ThePercentBox.Leave, AddressOf MakePercent
            AddHandler ThePercentBox.Enter, AddressOf MakeNumber


            RemoveHandler TheFundingBox.Leave, AddressOf MakeMoney
            RemoveHandler TheFundingBox.Enter, AddressOf MakeNumber

            AddHandler TheFundingBox.Leave, AddressOf MakeMoney
            AddHandler TheFundingBox.Enter, AddressOf MakeNumber



        End If
    End Sub

    Private Sub MakePercent(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Try
            DirectCast(sender, TextBox).Text = DirectCast(sender, TextBox).Text * 100
            DirectCast(sender, TextBox).Text = DirectCast(sender, TextBox).Text & "%"
        Catch ex As Exception

        End Try

      

    End Sub

    Private Sub MakeNumber(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Try
            DirectCast(sender, TextBox).Text = DirectCast(sender, TextBox).Text.Replace("£", "").Replace(",", "")

            If DirectCast(sender, TextBox).Text.Contains("%") Then
                DirectCast(sender, TextBox).Text = DirectCast(sender, TextBox).Text.Replace("%", "") / 100
            End If

            DirectCast(sender, TextBox).SelectAll()

        Catch ex As Exception

        End Try


    End Sub

    Private Sub MakeMoney(ByVal sender As System.Object, ByVal e As System.EventArgs)

        Try
            DirectCast(sender, TextBox).Text = Decimal.Parse(DirectCast(sender, TextBox).Text).ToString("c")
        Catch ex As Exception

        End Try

      


    End Sub

   
    Private Sub RecalcButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RecalcButton.Click
        RecalcMenu.Show(RecalcButton, New System.Drawing.Point(0, RecalcButton.Height))
    End Sub

    Private Sub RecalcFundingItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RecalcFundingItem.Click
        RecalcFunding()
    End Sub

    Private Sub RecalcPercentItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RecalcPercentItem.Click
        RecalcPercentage()

    End Sub
End Class